package com.h3c.ptability.controller;

import com.h3c.ptability.bo.EmailAttachmentBO;
import com.h3c.ptability.bo.SendEmailBO;
import com.h3c.ptability.entity.PtEmailRecord;
import com.h3c.ptability.mapstruct.PtEmailRecordMapstruct;
import com.h3c.ptability.service.IPtEmailRecordService;
import com.h3c.ptability.utils.EmailUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author chenyifan
 * @date 2022/6/14 13:40
 * 其他应用调用公共能力发送邮件相关接口
 */
@Slf4j
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/email")
public class EmailController {


    private final IPtEmailRecordService ptEmailRecordService;

    /**
     * 发送邮件接口
     *
     * @param emailBO 邮件信息
     * @return 发送状态
     */
    @PostMapping(value = "/sendEmailFile")
    public Map<String, String> sendEmail(@RequestBody SendEmailBO emailBO) {
        HashMap<String, String> result = null;
        try {
            result = EmailUtil.sendEmail(emailBO);
        } catch (Exception e) {
            log.error("公共能力发送邮件报错:", e);
        }
        if (result.get("state").equals("success")) {
            PtEmailRecord emailRecord = PtEmailRecordMapstruct.INSTANCE.bo2Entity(emailBO);
            //如果不需要记录内容
            if(Objects.nonNull(emailBO.getIsRecord()) && !emailBO.getIsRecord()){
                emailRecord.setContent(null);
            }
            emailRecord.setSendTime(new Date())
                    .setFileNameList(emailBO.getAttachmentBOList().stream()
                            .map(EmailAttachmentBO::getAttachmentName)
                            .collect(Collectors.toList()));
            ptEmailRecordService.save(emailRecord);
        }
        return result;
    }
}
